<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket消息系统</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.5.0/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .card {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 15px;
        }
        input, button {
            padding: 8px;
            margin: 5px;
            width: 100%;
            box-sizing: border-box;
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background: #0056b3;
        }
        button:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
        .connected {
            background: #d4edda;
            color: #155724;
        }
        .disconnected {
            background: #f8d7da;
            color: #721c24;
        }
        .messages {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            margin-top: 10px;
        }
        .message {
            padding: 8px;
            margin: 5px 0;
            border-left: 3px solid #007bff;
            background: #f8f9fa;
        }
        .message.broadcast {
            border-left-color: #28a745;
            background: #e8f5e8;
        }
        .config {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            padding: 10px;
            margin-bottom: 15px;
            border-radius: 4px;
        }
        .config input {
            width: 70%;
        }
    </style>
</head>
<body>
<h1>WebSocket消息系统</h1>

<div class="config">
    <h3>服务器配置</h3>
    <label for="serverUrl">服务器地址:</label>
    <input type="text" id="serverUrl" value="http://localhost:8080" placeholder="http://localhost:8080">
    <small>请输入完整的服务器地址，包括协议和端口</small>
</div>

<div class="card">
    <h3>用户连接</h3>
    <input type="text" id="userId" placeholder="请输入用户ID">
    <div>
        <button id="connectBtn">连接</button>
        <button id="disconnectBtn" disabled>断开</button>
    </div>
    <div id="connectionStatus" class="status disconnected">未连接</div>
</div>

<div class="card">
    <h3>发送消息</h3>
    <input type="text" id="toUser" placeholder="接收用户ID (多个用逗号分隔)">
    <input type="text" id="messageContent" placeholder="消息内容">
    <div>
        <button id="sendToUserBtn" disabled>发送给用户</button>
        <button id="sendToGroupBtn" disabled>发送给群组</button>
        <button id="sendBroadcastBtn" disabled>广播消息</button>
    </div>
</div>

<div class="card">
    <h3>消息记录</h3>
    <div id="messages" class="messages">
        <div>暂无消息</div>
    </div>
</div>

<script>
    // 全局变量
    let stompClient = null;
    let userId = null;
    let isConnected = false;
    let serverUrl = "http://localhost:8080"; // 默认服务器地址

    // 初始化函数
    function init() {
        // 从输入框获取服务器地址
        const serverUrlInput = document.getElementById('serverUrl');
        serverUrl = serverUrlInput.value.trim();
        if (!serverUrl) {
            serverUrl = "http://localhost:8080";
            serverUrlInput.value = serverUrl;
        }

        // 确保URL以/结尾
        if (!serverUrl.endsWith('/')) {
            serverUrl = serverUrl + '/';
        }

        console.log("使用服务器地址:", serverUrl);
    }

    // 连接WebSocket
    function connect() {
        // 初始化服务器地址
        init();

        userId = document.getElementById('userId').value.trim();

        if (!userId) {
            alert('请输入用户ID');
            return;
        }

        try {
            // 使用完整URL路径
            const socketUrl = `${serverUrl}ws`;
            console.log('尝试连接到:', socketUrl);

            // 创建SockJS实例，禁用凭证传输
            const socket = new SockJS(socketUrl, null, {
                transports: ['websocket', 'xhr-streaming', 'xhr-polling'],
                withCredentials: false // 禁用凭证传输
            });

            stompClient = Stomp.over(socket);

            // 禁用调试信息
            stompClient.debug = null;

            // 连接时不使用凭证
            stompClient.connect(
                {userId: userId},
                function(frame) {
                    console.log('连接成功:', frame);
                    isConnected = true;
                    updateConnectionStatus(true);

                    // 订阅个人消息
                    stompClient.subscribe('/user/queue/messages', function(message) {
                        const messageData = JSON.parse(message.body);
                        addMessageToDisplay(messageData);
                    });

                    // 订阅广播消息
                    stompClient.subscribe('/topic/broadcast', function(message) {
                        const messageData = JSON.parse(message.body);
                        addMessageToDisplay(messageData);
                    });

                    console.log('WebSocket连接成功建立');
                },
                function(error) {
                    console.error('连接失败:', error);
                    isConnected = false;
                    updateConnectionStatus(false);
                    alert('连接失败: ' + error);
                }
            );
        } catch (error) {
            console.error('创建连接时出错:', error);
            alert('创建连接时出错: ' + error.message);
        }
    }

    // 断开WebSocket连接
    function disconnect() {
        if (stompClient !== null) {
            stompClient.disconnect();
        }
        isConnected = false;
        updateConnectionStatus(false);
        console.log("连接已断开");
    }

    // 发送点对点消息
    function sendToUser() {
        if (!isConnected) {
            alert('请先连接WebSocket');
            return;
        }

        const toUser = document.getElementById('toUser').value.trim();
        const content = document.getElementById('messageContent').value.trim();

        if (!toUser || !content) {
            alert('请填写接收用户和消息内容');
            return;
        }

        sendMessageRequest('api/message/sendToUser', {
            fromUser: userId,
            toUser: toUser,
            content: content
        });
    }

    // 发送群组消息
    function sendToGroup() {
        if (!isConnected) {
            alert('请先连接WebSocket');
            return;
        }

        const toUsersInput = document.getElementById('toUser').value.trim();
        const content = document.getElementById('messageContent').value.trim();

        if (!toUsersInput || !content) {
            alert('请填写接收用户和消息内容');
            return;
        }

        const toUsers = toUsersInput.split(',').map(id => id.trim());

        sendMessageRequest('api/message/sendToGroup', {
            fromUser: userId,
            toUsers: toUsers,
            content: content
        });
    }

    // 发送广播消息
    function sendBroadcast() {
        if (!isConnected) {
            alert('请先连接WebSocket');
            return;
        }

        const content = document.getElementById('messageContent').value.trim();

        if (!content) {
            alert('请填写消息内容');
            return;
        }

        sendMessageRequest('api/message/broadcast', {
            fromUser: userId,
            content: content
        });
    }

    // 发送API请求的通用函数
    function sendMessageRequest(apiPath, data) {
        // 确保服务器地址是最新的
        init();

        const fullUrl = serverUrl + apiPath;
        console.log('发送请求到:', fullUrl, '数据:', data);

        fetch(fullUrl, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            credentials: 'same-origin' // 使用同源凭证策略
        })
            .then(response => {
                if (response.ok) {
                    document.getElementById('messageContent').value = '';
                    console.log('消息发送成功');
                } else {
                    alert('消息发送失败，状态码: ' + response.status);
                }
            })
            .catch(error => {
                console.error('发送消息时出错:', error);
                alert('消息发送失败: ' + error.message);
            });
    }

    // 更新连接状态
    function updateConnectionStatus(connected) {
        const statusElement = document.getElementById('connectionStatus');
        const connectBtn = document.getElementById('connectBtn');
        const disconnectBtn = document.getElementById('disconnectBtn');
        const sendButtons = document.querySelectorAll('#sendToUserBtn, #sendToGroupBtn, #sendBroadcastBtn');

        if (connected) {
            statusElement.textContent = '已连接 - 用户ID: ' + userId;
            statusElement.className = 'status connected';
            connectBtn.disabled = true;
            disconnectBtn.disabled = false;
            sendButtons.forEach(btn => btn.disabled = false);
        } else {
            statusElement.textContent = '未连接';
            statusElement.className = 'status disconnected';
            connectBtn.disabled = false;
            disconnectBtn.disabled = true;
            sendButtons.forEach(btn => btn.disabled = true);
        }
    }

    // 添加消息到显示区域
    function addMessageToDisplay(message) {
        const messagesContainer = document.getElementById('messages');

        // 移除"暂无消息"提示
        if (messagesContainer.children.length === 1 &&
            messagesContainer.children[0].textContent === '暂无消息') {
            messagesContainer.innerHTML = '';
        }

        const messageElement = document.createElement('div');
        messageElement.className = 'message';

        if (message.type === 'BROADCAST') {
            messageElement.classList.add('broadcast');
        }

        const messageTime = new Date(message.timestamp).toLocaleString();

        messageElement.innerHTML = `
                <div><strong>${message.fromUser}</strong> -> <strong>${message.toUser === 'all' ? '所有人' : message.toUser}</strong></div>
                <div>${message.content}</div>
                <div style="font-size: 12px; color: #666;">
                    ${messageTime} | ${message.type === 'BROADCAST' ? '广播' : (message.type === 'GROUP' ? '群组' : '点对点')}
                </div>
            `;

        messagesContainer.appendChild(messageElement);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    // 绑定事件
    document.getElementById('connectBtn').addEventListener('click', connect);
    document.getElementById('disconnectBtn').addEventListener('click', disconnect);
    document.getElementById('sendToUserBtn').addEventListener('click', sendToUser);
    document.getElementById('sendToGroupBtn').addEventListener('click', sendToGroup);
    document.getElementById('sendBroadcastBtn').addEventListener('click', sendBroadcast);

    // 服务器地址变更时重新初始化
    document.getElementById('serverUrl').addEventListener('change', function() {
        init();
        if (isConnected) {
            alert('服务器地址已更改，请重新连接');
            disconnect();
        }
    });

    // 初始状态
    updateConnectionStatus(false);
    init();
</script>
</body>
</html>